'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    /**
     * Add altering commands here.
     */
    await queryInterface.createTable('sys_user_roles', {
      id: {
        type: Sequelize.BIGINT,
        primaryKey: true,
        comment: '关联ID',
      },
      user_id: {
        type: Sequelize.BIGINT,
        allowNull: false,
        comment: '用户ID',
        references: {
          model: 'sys_users',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      role_code: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: '角色编码',
        references: {
          model: 'sys_roles',
          key: 'code',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      create_time: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.NOW,
        comment: '创建时间',
      },
      update_time: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.NOW,
        onUpdate: Sequelize.NOW,
        comment: '更新时间',
      },
    });

    // 添加联合唯一索引，确保一个用户不能重复关联同一个角色
    await queryInterface.addIndex('sys_user_roles', [ 'user_id', 'role_code' ], {
      unique: true,
      name: 'uk_user_role',
    });
  },

  async down(queryInterface, Sequelize) {
    /**
     * Add reverting commands here.
     */
    // 先删除外键约束
    await queryInterface.removeConstraint('sys_user_roles', 'sys_user_roles_ibfk_1');
    await queryInterface.removeConstraint('sys_user_roles', 'sys_user_roles_ibfk_2');
    // 再删除索引
    await queryInterface.removeIndex('sys_user_roles', 'uk_user_role');
    // 最后删除表
    await queryInterface.dropTable('sys_user_roles');
  },
};
